import socket
import sys, os
import time;
import struct

def createStatus(lno):
	status = list('0' * 16)
	card = list('0' * 6)
	bt = list(bin(lno)[2:])
	card[len(card) - len(bt):] = bt
	status[0] = '0'
	status[1] = '0'
	status[2:8] = card
	status[8] = '0'
	status[9] = '0'
	status[10] = '1'
	status[11] = '0'
	####
	status[12] = '0'
	status[13] = '0'
	status[14] = '0'
	status[15] = '0'

	rstatus = int(''.join(status), 2)
	return rstatus

#####################
def createCmd(cmdlen):
	cmddata = b''
	lctime = time.localtime()
	for x in xrange(0, cmdlen):
		tmy = lctime.tm_year - 2000
		tmm = lctime.tm_mon - 1
		tmd = lctime.tm_mday
		tmh = lctime.tm_hour
		tmi = lctime.tm_min
		tms = lctime.tm_sec
		cmddata += struct.pack('6B', int(str(tmy), 16), int(str(tmm), 16), int(str(tmd), 16), int(str(tmh), 16), int(str(tmi), 16), int(str(tms), 16))
		cmddata += struct.pack('H', createStatus(x))
		cmddata += struct.pack('3I', x, x + 2, x + 4)
		cmddata += struct.pack('4H', 0, 0 ,0 ,0)
		cmddata += struct.pack('2H', 0, 0)

	return cmddata
################################################################
	
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
addr = ('localhost', 5000)

#fp = open('test.bin', 'rb')
#data = fp.read(1024);

#fp.close();

ret = sock.connect(addr)
#data = b'\x00\x00' + data


## set comid
data = b'\x02\x03\x04'
data += struct.pack('H', 3)
data += struct.pack('B', 0xF5)
data += struct.pack('H', 1)
data += struct.pack('B', 0)
data += struct.pack('B', 0x03)

################
cmdnums = 64

packdata = b'\x02\x03\x04'
packdata += struct.pack('H', cmdnums * 32 + 1)
packdata += struct.pack('B', 0xC2)
packdata += createCmd(cmdnums)
packdata += '\x00\x03'
print(len(packdata));
while 1:
	sock.send(data)
	bt = sock.recv(1024);
	#fmt = '%dB' % len(bt);
	#msg = strucOt.unpack(fmt, bt);
	#print(msg)
	print(bt)
	sock.send(packdata[:100])# + packdata[100:])
	time.sleep(1)
	sock.send(packdata[100:])
	ct = sock.recv(1024);
	print(ct)
	#print(ord(bt[0]));
	break
print(ret)

sock.close()
